<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频监控系统 - 登录</title>
    <!-- 使用本地静态资源 -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/font-awesome.min.css') }}">
    <style>
        :root {
            --primary-color: #4e54c8;
            --secondary-color: #8f94fb;
            --text-color: #f8f9fa;
            --bg-color: #1a2a6c;
            --card-bg: rgba(255, 255, 255, 0.1);
        }

        body {
            background: linear-gradient(135deg, var(--bg-color), #2c3e50);
            color: var(--text-color);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
        }

        .login-container {
            width: 100%;
            max-width: 450px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .login-card {
            background: var(--card-bg);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .login-header h2 {
            color: white;
            font-weight: 600;
            margin-bottom: 10px;
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .login-header p {
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.9rem;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .input-group {
            margin-bottom: 15px;
        }

        .input-group-text {
            background: rgba(0, 0, 0, 0.3);
            border: none;
            color: rgba(255, 255, 255, 0.8);
            width: 40px;
            display: flex;
            justify-content: center;
        }

        .form-control {
            background: rgba(0, 0, 0, 0.3);
            border: none;
            color: white;
            height: 45px;
        }

        .form-control:focus {
            background: rgba(0, 0, 0, 0.4);
            color: white;
            box-shadow: 0 0 0 0.25rem rgba(78, 84, 200, 0.25);
        }

        .btn-login {
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
            border: none;
            height: 45px;
            font-weight: 600;
            width: 100%;
            margin-top: 10px;
            transition: all 0.3s;
        }

        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }

        .alert {
            border-radius: 8px;
        }

        .footer {
            text-align: center;
            margin-top: 20px;
            color: rgba(255, 255, 255, 0.6);
            font-size: 0.8rem;
        }

        /* 标签文字样式优化 */
        .form-label {
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 8px;
            font-size: 0.9rem;
            display: block;
        }

        /* 输入组图标优化 */
        .input-group-text {
            background: rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: rgba(255, 255, 255, 0.8);
        }

        /* 新增的placeholder样式 */
        .form-control::placeholder {
            color: rgba(255, 255, 255, 0.6) !important;
            opacity: 1;
        }

        .form-control:focus::placeholder {
            color: rgba(255, 255, 255, 0.3) !important;
        }

        /* 兼容性处理 */
        .form-control::-webkit-input-placeholder { /* Chrome/Opera/Safari */
            color: rgba(255, 255, 255, 0.6);
        }
        .form-control::-moz-placeholder { /* Firefox 19+ */
            color: rgba(255, 255, 255, 0.6);
            opacity: 1;
        }
        .form-control:-ms-input-placeholder { /* IE 10+ */
            color: rgba(255, 255, 255, 0.6);
        }
        .form-control:-moz-placeholder { /* Firefox 18- */
            color: rgba(255, 255, 255, 0.6);
            opacity: 1;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* 响应式调整 */
        @media (max-width: 576px) {
            .login-card {
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <h2>视频监控系统</h2>
                <p>安全登录访问监控平台</p>
            </div>

            {% if error %}
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {{ error }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            {% endif %}

            <form id="loginForm" method="POST" action="{{ url_for('api_login') }}">
                <input type="hidden" id="publicKey" value="{{ public_key }}">

                <div class="form-group">
                    <label for="username" class="form-label">用户名</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-user"></i></span>
                        <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名" required>
                    </div>
                </div>

                <div class="form-group">
                    <label for="password" class="form-label">密码</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-lock"></i></span>
                        <input type="password" class="form-control" id="password" placeholder="请输入密码" required>
                        <input type="hidden" name="password" id="encryptedPassword">
                    </div>
                </div>

                <button type="submit" class="btn btn-primary btn-login">
                    <i class="fa fa-sign-in-alt"></i> 登录
                </button>
            </form>

            <div class="footer">
                &copy; 2025 视频监控系统 | 版本 1.0.0
            </div>
        </div>
    </div>

    <!-- 使用本地静态资源 -->
    <script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jsencrypt.min.js') }}"></script>

    <script>
        // 定义全局错误提示函数
        function showError(message) {
            const loginForm = document.getElementById('loginForm');
            if (!loginForm) return;

            // 移除旧错误提示
            const oldAlert = document.querySelector('.alert-danger');
            if (oldAlert) oldAlert.remove();

            // 创建新错误提示
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-danger mt-3';
            alertDiv.innerHTML = `
                <i class="fa fa-exclamation-circle me-2"></i>
                ${message}
                <button type="button" class="btn-close float-end" data-bs-dismiss="alert"></button>
            `;

            // 插入到表单前
            loginForm.parentNode.insertBefore(alertDiv, loginForm.nextSibling);

            // 5秒后自动消失
            setTimeout(() => {
                alertDiv.classList.add('fade');
                setTimeout(() => alertDiv.remove(), 150);
            }, 5000);
        }

        // 验证公钥格式
        function validatePublicKey(publicKey) {
            if (!publicKey) return false;

            // 简单格式验证
            return publicKey.includes('-----BEGIN PUBLIC KEY-----') &&
                   publicKey.includes('-----END PUBLIC KEY-----');
        }

        function prepareLogin(form) {
            const password = document.getElementById('password').value;
            const publicKey = document.getElementById('publicKey').value;

            console.log("原始密码:", password);
            console.log("使用的公钥:", publicKey);

            const encrypted = encryptPassword(password, publicKey);
            if (!encrypted) return false;

            console.log("加密结果:", encrypted);
            document.getElementById('encryptedPassword').value = encrypted;
            return true;
        }

        function encryptPassword(password, publicKey) {
            try {
                console.log("加密前的密码:", password);
                const encrypt = new JSEncrypt();
                encrypt.setPublicKey(publicKey);
                const encrypted = encrypt.encrypt(password);
                console.log("加密后的结果:", encrypted);
                return encrypted;
            } catch (e) {
                console.error("加密错误:", e);
                return null;
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            const loginForm = document.getElementById('loginForm');
            const publicKey = document.getElementById('publicKey').value;

            // 验证公钥格式
            if (!publicKey ||
                !publicKey.includes('-----BEGIN PUBLIC KEY-----') ||
                !publicKey.includes('-----END PUBLIC KEY-----')) {
                showError('系统安全配置异常，请刷新页面');
                return;
            }

            // 初始检查公钥
            if (!validatePublicKey(publicKey)) {
                showError('系统安全配置异常，请刷新页面');
                return;
            }

            // 实时加密密码
            document.getElementById('password').addEventListener('input', function() {
                const password = this.value;
                if (password) {
                    const encrypted = encryptPassword(password, publicKey);
                    if (encrypted) {
                        document.getElementById('encryptedPassword').value = encrypted;
                    } else {
                        document.getElementById('encryptedPassword').value = '';
                    }
                }
            });

            document.getElementById('loginForm').addEventListener('submit', async function(e) {
                e.preventDefault();

                const password = document.getElementById('password').value;
                const publicKey = document.getElementById('publicKey').value;
                const encrypted = encryptPassword(password, publicKey);

                if (!encrypted) {
                    alert("加密失败");
                    return false;
                }

                document.getElementById('encryptedPassword').value = encrypted;
                document.getElementById('password').value = '';

                // 发送登录请求
                try {
                    const response = await fetch(this.action, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: new URLSearchParams(new FormData(this))
                    });

                    const data = await response.json();

                    if (data.success) {
                        // 存储 Token 到 localStorage 或 sessionStorage
                        localStorage.setItem('token', data.token);
                        localStorage.setItem('user', JSON.stringify(data.user));

                        // 跳转到首页
                        document.cookie = `token=${data.token}; path=/`;
                        window.location.href = '/index';  // 或你的首页路径
                    } else {
                        alert(data.error || "登录失败");
                    }
                } catch (error) {
                    console.error("登录错误:", error);
                    alert("登录请求失败");
                }
            });

            // 监听重定向事件
            window.addEventListener('beforeunload', function(e) {
                if (window.location.pathname !== '/login') {
                    console.log('检测到页面重定向，即将跳转到:', window.location.href);
                }
            });
        });
    </script>
</body>
</html>